package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //log.info("开始插入填充...");
        this.strictInsertFill(metaObject, "createBy", String.class, getLoginUserId());
        this.strictInsertFill(metaObject, "updateBy", String.class, getLoginUserId());
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        this.strictInsertFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //log.info("开始更新填充...");
        this.setFieldValByName("updateBy", getLoginUserId(),metaObject);
        this.setFieldValByName("updateTime",DateUtils.getNowDate(), metaObject);
    }

    /**
     * 获取当前登录人的ID
     * @return  登录人ID
     */
    public String getLoginUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser)) {
            return "0";
        }
        return loginUser.getUserId().toString();
    }
}